/*
 * @Author: 1453937336@qq.com 1453937336@qq.com
 * @Date: 2024-04-28 10:29:18
 * @LastEditors: 1453937336@qq.com 1453937336@qq.com
 * @LastEditTime: 2024-06-12 10:03:35
 * @FilePath: \itforce-hris\src\store\modules\loginStore.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { UseLoginApi } from '@/api/login/login';
import { AES_ECB_ENCRYPT } from '@/utils/encrypt'
import { getToken, setToken, removeToken, getCookies, setCookie, removeCookie, getTokenName } from '@/utils/auth'
import store from '..';
import { Session } from '@/utils/storage';

// import store from '..';

const state: any = {
  state: {
    token: getToken(),
    id: "",
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
    customFieldModule: [],
    userInfo: {},
    ifHr: false
  }, //设置全局弹窗状态
};

const mutations: any = {
  // 登陆
  SET_TOKEN: (state: any, token: String) => {
    state.token = token;
  },
  SET_ID: (state: any, id: [String, Number]) => {
    state.id = id;
  },
  SET_NAME: (state: any, name: String) => {
    state.name = name;
  },
  SET_AVATAR: (state: any, avatar: String) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state: any, roles: [[], {}]) => {
    state.roles = roles;
    // sessionStorage.setItem("MY_VUEX", state.roles);
    // Session.set("MY_VUEX", state.roles)
  },
  SET_PERMISSIONS: (state: any, permissions: [[], {}]) => {
    state.permissions = permissions;
  },
  SET_USERINFO: (state: any, data: {}) => {
    state.userInfo = data;
    sessionStorage.setItem("userInfo", JSON.stringify(data));
  },
  SET_IFHR: (state: any, data: {}) => {
    console.log('actions', data);
    state.ifHr = data
    Session.set('ifHr', data)
  }
};
interface userInfo {
  email: String,
  password: String,
  loginType: Number
}
const actions = {
  // 登陆
  Login({ commit, dispatch }: any, userInfo: userInfo) {
    // 密码加密
    const data: any = cloneDeep(userInfo)
    data.password = AES_ECB_ENCRYPT(data.password, data.email)
    return new Promise((resolve: any, reject: any) => {
      UseLoginApi(data).then(async (res: any) => {
        if (res.code === 200) {
          setCookie(res.data.tokenName, res.data.tokenValue, res.data.tokenTimeout)
          commit('SET_TOKEN', res.data.tokenValue);
          commit("SET_USERINFO", res.data ?? {});
          commit("SET_ROLES", res.data.roleList ?? [])
          dispatch('getIfHr');
          store.dispatch('GenerateRoutes', res.data.menuTreeList ?? [])
        }
        resolve();
      }).catch(error => {
        reject(error)
      })
    })
  },
  getIfHr({ commit }: any) {
    commit("SET_IFHR", false);
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
